package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author 应癫
 */
public class DruidUtils {

    private DruidUtils(){
    }

    private static DruidDataSource druidDataSource;
    private static Boolean started = false;
    private static String db = null;


//    static {
//        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
//        druidDataSource.setUrl("jdbc:mysql://localhost:3306/lagou_java");
//        druidDataSource.setUsername("root");
//        druidDataSource.setPassword("MYSQLglm!1");
//    }

    public static DruidDataSource getInstance() throws Exception {
        druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("MYSQLglm!1");
        String dbUrl = "jdbc:mysql://localhost:3306/";
//        String db = "lagou_java";
        if (!started) {
            db = getDbName();
        }
        System.out.println("The db is: " + db);
        druidDataSource.setUrl(dbUrl + db);
        return druidDataSource;
    }

    private static CuratorFramework getZkClient() {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 5))
                .build();

        client.start();
        System.out.println("Zookeeper session established.");

        final NodeCache nodeCache = new NodeCache(client, "/lg-webdb", false);
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            public void nodeChanged() throws Exception {
                System.out.println("当前节点："+nodeCache.getCurrentData());
                ChildData childData = nodeCache.getCurrentData();
                String db = new String(childData.getData());
                System.out.println("//the new db:" + db);
                changeDb(db);
            }
        });
        //如果为true则首次不会缓存节点内容到cache中，默认为false,设置为true首次不会触发监听事件
        try {
            nodeCache.start(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return client;
    }

    private static void changeDb(String nDb) {
        db = nDb;
    }

    private static String getDbName() throws Exception {
        byte[] bytes = getZkClient().getData().forPath("/lg-webdb");
        started = true;
        return new String(bytes);
    }

}
